package com.eastedu.superise.scanner;

import com.eastedu.util.SqlHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Objects;

/**
 * 历史数据扫描器
 *
 * @author superman
 */
@Slf4j
public class HistoricalDataScanner {

    private final JdbcTemplate jdbcTemplate;

    /**
     * Instantiates a new Historical data scanner.
     *
     * @param jdbcTemplate the jdbc template
     */
    public HistoricalDataScanner(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * Scan.
     *
     * @param <T>      the type parameter
     * @param sql      the sql
     * @param callback the callback
     * @param clazz    the clazz
     */
    public <T> void scan(String sql, Callback<T> callback, Class<T> clazz) {
        String countSql = SqlHelper.generateCountQuery(sql);
        Long count = jdbcTemplate.queryForObject(countSql, Long.class);
        if (Objects.isNull(count) || count == 0) {
            log.info("数据源[{}]无数据， 同步任务结束", clazz.getSimpleName());
            return;
        }
        jdbcTemplate.query(con -> {
            PreparedStatement preparedStatement =
                    con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            preparedStatement.setFetchSize(Integer.MIN_VALUE);
            preparedStatement.setFetchDirection(ResultSet.FETCH_FORWARD);
            return preparedStatement;
        }, new CustomResultSetExtractor<>(count, callback, clazz));

    }

}
